package com.ruoyi.project.bas.product.controller;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.bas.product.domain.BasProduct;
import com.ruoyi.project.bas.product.service.IBasProductService;
import com.ruoyi.web.controller.common.BusinessException;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 物品资料Controller
 * 
 * @author ruoyi
 * @date 2023-04-04
 */
@Controller
@RequestMapping("/bas/product")
public class BasProductController extends BaseController
{
    private String prefix = "bas/product";

    private final static Map<String, BasProduct> products = new LinkedHashMap<String, BasProduct>();

    @Autowired
    private IBasProductService basProductService;

    @GetMapping()
    public String product()
    {
        return prefix + "/product";
    }

    /**
     * 查询物品资料列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BasProduct basProduct)
    {
        startPage();
        List<BasProduct> list = basProductService.selectBasProductList(basProduct);
        return getDataTable(list);
    }
    @PostMapping("/listAll")
    @ResponseBody
    public TableDataInfo listAll(BasProduct basProduct)
    {
        startPage();
        List<BasProduct> list = basProductService.selectBasProductListAll(basProduct);
        return getDataTable(list);
    }
    /**
     * 导出物品资料列表
     */
    @Log(title = "物品资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BasProduct basProduct)
    {
        List<BasProduct> list = basProductService.selectBasProductList(basProduct);
        ExcelUtil<BasProduct> util = new ExcelUtil<BasProduct>(BasProduct.class);
        return util.exportExcel(list, "物品资料数据");
    }

    /**
     * 新增物品资料
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存物品资料
     */
    @Log(title = "物品资料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BasProduct basProduct)
    {
        return toAjax(basProductService.insertBasProduct(basProduct));
    }

    /**
     * 修改物品资料
     */
    @GetMapping("/edit/{productGuid}")
    public String edit(@PathVariable("productGuid") String productGuid, ModelMap mmap)
    {
        BasProduct basProduct = basProductService.selectBasProductByProductGuid(productGuid);
        mmap.put("basProduct", basProduct);
        return prefix + "/edit";
    }

    /**
     * 修改保存物品资料
     */
    @Log(title = "物品资料", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BasProduct basProduct)
    {
        return toAjax(basProductService.updateBasProduct(basProduct));
    }

    /**
     * 删除物品资料
     */
    @Log(title = "物品资料", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(basProductService.deleteBasProductByProductGuids(ids));
    }


    /**
     * 下载模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<BasProduct> util = new ExcelUtil<BasProduct>(BasProduct.class);
        return util.importTemplateExcel("物料信息");
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BasProduct> util = new ExcelUtil<BasProduct>(BasProduct.class);
        List<BasProduct> productList = util.importExcel(file.getInputStream());

        String message = importUser(productList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 导入用户数据
     *
     * @param productList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    public String importUser(List<BasProduct> productList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(productList) || productList.size() == 0)
        {
            throw new BusinessException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasProduct product : productList)
        {
            try
            {
                // 验证是否存在这个用户
                boolean userFlag = false;
                for (Map.Entry<String, BasProduct> entry : products.entrySet())
                {
                    if (entry.getValue().getProductId().equals(product.getProductId()))
                    {
                        userFlag = true;
                        break;
                    }
                }
                if (!userFlag)
                {
                    String productGuid = UUID.randomUUID().toString();
                    product.setProductGuid(productGuid);
//                    没有此字段
//                    product.setProductHeight(new BigDecimal(1));
//                    product.setProductWidth(new BigDecimal(1));
//                    product.setProductLength(new BigDecimal(1));
                    basProductService.insertBasProduct(product);
                    products.put(product.getProductId(), product);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料 " + product.getProductName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    products.put(product.getProductId(), product);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、物料 " + product.getProductName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、物料 " + product.getProductName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料 " + product.getProductName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
